package com.changgou.wbe.geteway.filter;

import com.changgou.wbe.geteway.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//全局过滤器
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthService authService;

    @Override
    public Mono <Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断请求路径
        ServerHttpRequest request = exchange.getRequest ();
        ServerHttpResponse response = exchange.getResponse ();

        //请求url获取路径
        String path = request.getURI ().getPath ();
        if ( "/api/oauth/login".equals (path)||!UrlFilter.hasAuthorize (path)) {
            return chain.filter (exchange);
        }
        //从就的去coo里番问
        String jti = authService.getJtiFromCookie (request);
        if ( StringUtils.isEmpty (jti) ) {
            response.setStatusCode (HttpStatus.UNAUTHORIZED);
            return response.setComplete ();
        }
        //coo有就要去redis里拿去
        String jwt = authService.getJtiFromRedis (jti);
        //jwt存在   就要对但前  携带临牌信息
        if ( StringUtils.isEmpty (jwt) ) {
            //拒绝访问
            response.setStatusCode (HttpStatus.UNAUTHORIZED);
            return response.setComplete ();
        }
        //对象曾强，携带令牌
        request.mutate ().header ("Authorization", "Bearer" + jwt);
        //放行
        return chain.filter (exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
